﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace HybridLab.Workflow.Activities.UI
{
	public partial class ErrorControl : UserControl
	{
		internal delegate void LinkClickedDelegate(LinkLabel.Link link);

		private LinkClickedDelegate callBack;
		private bool isMaximumSizeSet;
		private Size maximumSize;

		internal ErrorControl()
		{
			maximumSize = Size.Empty;
			InitializeComponent();
			errorLayoutPanel.Visible = false;
			//errorPictureBox.Image = WizardResources.Icon_Warning16;
			UpdateLabelSize();
			ParentChanged += new EventHandler(ErrorDisplayControl_ParentChanged);
		}

		internal ErrorControl(Size maximumSize)
			: this()
		{
			this.maximumSize = maximumSize;
			isMaximumSizeSet = true;
			errorMessageLabel.LinkClicked += new LinkLabelLinkClickedEventHandler(errorMessageLabel_LinkClicked);
		}

		private void ErrorDisplayControl_ParentChanged(object sender, EventArgs e)
		{
			UpdateLabelSize();
		}

		private void errorMessageLabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
		{
			if ((errorMessageLabel.Links != null) && errorMessageLabel.Links.Contains(e.Link))
			{
				errorMessageLabel.Links[this.errorMessageLabel.Links.IndexOf(e.Link)].Visited = true;
			}
			if (callBack != null)
			{
				callBack(e.Link);
			}
		}

		internal void SetErrorMessage(string message)
		{
			SetMessage(message, true, 0, 0, null);
		}

		internal void SetInformationMessage(string message)
		{
			SetMessage(message, false, 0, 0, null);
		}

		internal void SetMessage(string message, bool isError, int linkStart, int linkLength, LinkClickedDelegate callback)
		{
			errorPictureBox.Visible = isError;
			if (string.IsNullOrEmpty(message))
			{
				errorMessageLabel.Text = string.Empty;
				errorLayoutPanel.Visible = false;
			}
			else
			{
				errorLayoutPanel.Visible = true;
				errorMessageLabel.Text = message;
			}
			errorMessageLabel.LinkArea = new LinkArea(linkStart, linkLength);
			callBack = callback;
		}

		private void UpdateLabelSize()
		{
			if (base.Parent != null)
			{
				errorLayoutPanel.SuspendLayout();
				base.SuspendLayout();
				Size empty = isMaximumSizeSet ? (maximumSize - errorPictureBox.Size) : new Size(base.Parent.Size.Width, 0);
				if ((empty.Width < 0) || (empty.Height < 0))
				{
					empty = Size.Empty;
				}
				this.errorMessageLabel.MaximumSize = empty;
				this.errorLayoutPanel.ResumeLayout(false);
				this.errorLayoutPanel.PerformLayout();
				base.ResumeLayout(false);
				base.PerformLayout();
			}
		}
	}
}
